package userPages;

import pages.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBUtils;

import templates.Template;

/**
 * Servlet implementation class ViewReservations
 */
public class ViewReservations extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewReservations() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");

		try {
			Template template = new Template(
					"user_templates\\user_reservations");

			addRows(template, request.getUserPrincipal().getName());
			template.addChange("error", "");
			response.getOutputStream().print(
					template.createPage(
							"Instruments Labaratory: View Resrvations", LMUtils
									.getUserLogin(request)));
		} catch (Exception e) {
			ErrorPage.printErrorPage(e.getMessage(), request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * Create rowas of reservation from DB
	 * @param template
	 * @param username
	 */
	private void addRows(Template template, String username) {
		Connection conn = null;
		PreparedStatement selectUserStmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtils.getConnection();
			String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
			String date = sdf.format(cal.getTime());

			selectUserStmt = conn
					.prepareStatement("SELECT r.starttime, r.endtime, i.id,i.name as name,it.name as type, i.isActive as isActive "
							+ "FROM reservations as r,instruments as i, instrumenttypes as it "
							+ "WHERE r.userlogin=? && r.instrumentid = i.id && i.typeid = it.id && r.endtime>? "
							+ "ORDER BY r.starttime;");
			selectUserStmt.setString(1, username);
			selectUserStmt.setString(2, date);
			rs = selectUserStmt.executeQuery();
			if (rs == null || !rs.next()) {
				template.addChange("rows", "");
				return;
			} else {
				int row = 1;
				String rows = "";
				do {
					String start = rs.getString("starttime");
					String end = rs.getString("endtime");

					Date dateStart = sdf.parse(start);
					Date dateEnd = sdf.parse(end);

					start = sdf.format(dateStart);
					end = sdf.format(dateEnd);

					int minutes = (int) ((dateEnd.getTime() - dateStart
							.getTime()) / (1000 * 60));
					int hours = minutes / 60;
					minutes = minutes % 60;

					rows += "<tr style=\"color:"
							+ (rs.getBoolean("isActive") ? "green" : "red")
							+ "\">"

							+ "<td>"
							+ rs.getString("type")
							+ "</td>"
							+ "<td><a href=\"/severandstemka/users/ViewInstrument?id="
							+ rs.getString("id")
							+ "\">"
							+ rs.getString("name")
							+ "</a></td>"
							+ "<td>"
							+ start
							+ "</td>"
							+ "<td>"
							+ end
							+ "</td>"
							+ "<td>"
							+ hours
							+ " Hours "
							+ minutes
							+ " Min</td>"
							+ "<td><input type='submit' class='intable' value='Delete' id='del"
							+ row + "' onclick='JavaScript:deleteReservation("
							+ row + "," + rs.getString("id") + ")' /></td>"
							+ "</tr>";

					row++;

				} while (rs.next());
				template.addChange("rows", rows);
			}
		} catch (Exception e) {
			template.addChange("rows", e.getMessage());
			return;
		} finally {
			DBUtils.close(rs);
			DBUtils.close(selectUserStmt);
			DBUtils.close(conn);
		}

	}

}
